<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 定义拦截操作，一般我们拦截操作后进行界面的更新
        const reactiveHandler = {
            get(target, key) {
                if (key === '_is_reactive') return true
                return Reflect.get(target, key)
            },

            set(target, key, value) {
                const result = Reflect.set(target, key, value)
                console.log('数据已更新, 去更新界面')
                return result
            },

            deleteProperty(target, key) {
                const result = Reflect.deleteProperty(target, key)
                console.log('数据已删除, 去更新界面')
                return result
            },
        }

        // 定义shallowReactive函数
        function shallowReactive(obj) {
            return new Proxy(obj, reactiveHandler)
        }

        // 定义reactive函数，通过递归实现全部的响应式(对于每一个对象进行代理)
        function reactive(target) {
            if (target && typeof target === 'object') {
                if (target instanceof Array) { // 数组
                    target.forEach((item, index) => {
                        target[index] = reactive(item)
                    })
                } else { // 对象
                    Object.keys(target).forEach(key => {
                        target[key] = reactive(target[key])
                    })
                }

                const proxy = new Proxy(target, reactiveHandler)
                return proxy
            }

            return target
        }


        // 测试自定义shallowReactive 
        const proxy = shallowReactive({
            a: {
                b: 3
            }
        })

        proxy.a = { b: 4 } // 劫持到了
        proxy.a.b = 5 // 没有劫持到


        // 测试自定义reactive
        const obj = {
            a: 'abc',
            b: [{ x: 1 }],
            c: { x: [11] },
        }

        const proxy = reactive(obj)
        console.log(proxy)
        proxy.b[0].x += 1
        proxy.c.x[0] += 1
    </script>
</body>

</html>